package jblip.util.json;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class JSONObject implements JSONValue<Map<JSONString, JSONValue<?>>> {
  
  private final Map<JSONString, JSONValue<?>> items;

  public JSONObject() {
    items = new HashMap<JSONString, JSONValue<?>>();
  }

  public JSONValue<?> get(String key) {
    if (key == null) {
      throw new NullPointerException("Null key parameter");
    }

    try {
      JSONValue<?> val = items.get(new JSONString(key));
      if (val instanceof JSONNull) {
        return null;
      } else {
        return val;
      }
    } catch (JSONException e) {
      return null;
    }
  }
  
  public Integer getInteger(String key) {
    JSONNumber number = (JSONNumber) get(key);
    if (number == null) {
      return null;
    }
    BigDecimal bigint = number.getValue();
    return bigint.intValueExact();
  }
  
  public BigDecimal getBigDecimal(String key) {
    JSONNumber number = (JSONNumber) get(key);
    if (number == null) {
      return null;
    }
    return number.getValue();
  }
  
  public String getString(String key) {
    JSONString str = (JSONString) get(key);
    if (str == null) {
      return null;
    }
    return str.getValue();
  }
  
  public Boolean getBoolean(String key) {
    JSONBoolean bool = (JSONBoolean) get(key);
    if (bool == null) {
      return null;
    }
    return bool.getValue();
  }
  
  public JSONArray getJSONArray(String key) {
    return (JSONArray) get(key);
  }
  
  public JSONObject getJSONObject(String key) {
    return (JSONObject) get(key);
  }
  
  public Boolean isJSONNull(String key) {
    JSONValue<?> jsonnull = get(key);
    return (jsonnull instanceof JSONNull);
  }
  
  public boolean contains(String key) {
    if(key == null) {
      throw new NullPointerException("Null key parameter");
    }

    try {
      return items.containsKey(new JSONString(key));
    } catch (JSONException e) {
      return false;
    }
  }
  
  public void put(JSONString key, JSONValue<?> value) {
    if (items.containsKey(key)) {
      System.err.println("Object already contains key " + key);
    }

    items.put(key, value);
  }

  public Map<JSONString, JSONValue<?>> getValue() {
    return items;
  }
}
